package com.business.lgh.naocs.naming.controllers;

import com.alibaba.fastjson.JSONArray;
import com.business.lgh.nacos.api.naming.pojo.Instance;
import com.business.lgh.naocs.naming.consistency.ConsistencyService;
import com.business.lgh.naocs.naming.consistency.KeyBuilder;
import com.business.lgh.naocs.naming.consistency.ephemeral.distro.DistroConsistencyServiceImpl;
import com.business.lgh.naocs.naming.constant.UtilsAndCommons;
import com.business.lgh.naocs.naming.core.ServerMemberManager;
import com.business.lgh.naocs.naming.core.ServiceManager;
import com.business.lgh.naocs.naming.core.pojo.InstanceWrapper;
import com.business.lgh.naocs.naming.core.pojo.Instances;
import com.business.lgh.naocs.naming.misc.Datum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author lgh
 * @version V1.0
 * @Package com.business.lgh.naocs.naming.controllers
 * @date 2020/6/29 5:02 下午
 */
@RestController
@RequestMapping(UtilsAndCommons.NACOS_NAMING_CONTEXT + "/distro")
public class DistroController {

    @Autowired
    DistroConsistencyServiceImpl consistencyServiceImpl;

    @Autowired
    ServiceManager serviceManager;

    @GetMapping("/getAllDatums")
    public String getDatums() {
        String data = JSONArray.toJSONString(consistencyServiceImpl.getDataStore());
        return data;
    }


    @PutMapping("/datum")
    public String onSyncDatums(@RequestBody Map<String, Datum> dataMap) {
        if (dataMap != null) {
            for (Map.Entry<String, Datum> entry : dataMap.entrySet()) {
                String datumKey = entry.getKey();
                //获取实例集合
                Instances instances = entry.getValue().getValue();
                //判断是否有该service
                if (consistencyServiceImpl.getDataStore().get(datumKey) == null) {
                    InstanceWrapper instance = instances.getInstances().get(0);
                    serviceManager.createEmptyService(instance.getNamespaceId(), instance.getServiceName(), instance.isEphemeral());
                }
                consistencyServiceImpl.onPut(datumKey, instances);
            }
        }
        return "ok";
    }
}
